package com.baizhi.utils;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

/**
 * @Auther: dlh
 * @Date: 2020/12/9
 * @ClassName: JWTUtils
 * @Describle: 技术在灵魂面前必输
 * @Version:1.0
 **/
public class JWTUtils {

    private static final String SING = "!Q@W3$%^T";

    /**
     * 生成token header.payload.sing
     */
    public static String getToken(Map<String, String> map) {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, 7); //默认7天过期
        //创建jwt builder
        JWTCreator.Builder builder = JWT.create();
        //paylodad
        map.forEach((k, v) -> {
            builder.withClaim(k, v);
        });
        String token = builder.withExpiresAt(instance.getTime()) //指定过期时间
                .sign(Algorithm.HMAC256(SING));//SING
        return token;
    }

    /**
     * 验证token
     */
    public static DecodedJWT verifyToken(String token) {
       return JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
    }
}
